﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;

[ExecuteInEditMode]
public class UIToggle : MonoBehaviour, IPointerClickHandler
{
    [System.Serializable]
    public struct HandleState
    {
        public Color color;
        public Sprite sprite;
        public Vector3 position;
    }

    public Image background;
    public Image mark;
    public Image handle;

    public List<HandleState> handleStates = new List<HandleState>();

    [SerializeField]
    private UnityEvent onEventToggle;
    public Action<int> onToggle;

    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value > handleStates.Count - 1) value = handleStates.Count - 1;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }

#if UNITY_EDITOR
    bool _dirty = false;
    private void OnValidate()
    {
        if (handleStates == null || handleStates.Count <= 0) return;
        if (_index > handleStates.Count - 1) _index = handleStates.Count - 1;
        if (_index < 0) _index = 0;
        _dirty = true;
    }


    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }

#endif

    private void UpdateFromIndex(int index)
    {
        if (this.handleStates.Count <= 0) return;
        var data = this.handleStates[index];
        //this.handle.color = data.color;
        this.handle.transform.localPosition = data.position;
        this.handle.sprite = data.sprite;
        if(this.mark)this.mark.gameObject.SetActive(index >= 1);
        //onEventToggle?.Invoke();
        
        //onToggle?.Invoke(index);
    }


    [EditorButton]
    private void SaveHandleState()
    {
        handleStates.Add(new HandleState()
        {
            sprite = this.handle.sprite,
            position = this.handle.transform.localPosition,
            //color = this.handle.color
        });
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        this.index = (this.index + 1) % this.handleStates.Count;
        onEventToggle?.Invoke();

        onToggle?.Invoke(index);
    }
}
